﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using FaceSharp.Api.GraphApi;
using FaceSharp.Api.Types;
using Newtonsoft.Json.Linq;
using FaceSharp.Api.Common;

namespace FaceSharp.Api.Objects
{
    public class Links : GraphBase
    {
        public Links(IFacebookCore facebookCore): base(facebookCore)
        {
        }

        public IEnumerable<LinkType> List(string userId)
        {
            Trace.Write("Begin Request", "Facebook.Objects.Links.List");
            var jObject = MakeGraphRequest(userId, "links");
            var links = new List<LinkType>();

            if (jObject != null)
            {
                var jData = (JArray)jObject["data"];
                links = (from link in jData
                         select ParseLink(link)
                        ).ToList();
            }
            Trace.Write("End Request", "Facebook.Objects.Links.List");
            return links.AsEnumerable();
        }

        public LinkType Get(long linkId)
        {
            Trace.Write("Begin Request", "Facebook.Objects.Links.Get");
            var jObject = MakeGraphRequest(linkId.ToString());
            var link = ParseLink(jObject);
            Trace.Write("End Request", "Facebook.Objects.Links.Get");
            return link;
        }


        private static LinkType ParseLink(JToken jObject)
        {
            Trace.Write("Begin Request", "Facebook.Objects.Links.ParseLink");

            var link = new LinkType();
            if (jObject != null)
            {
                Trace.Write("JSONData:" + jObject.ToString(), "Facebook.Objects.Links.ParseLink");

                link = new LinkType()
                {
                    Id = long.Parse((string)jObject["id"]),
                    Link = (string)jObject["link"],
                    Name = (string)jObject["name"],
                    Caption = (string)jObject["caption"],
                    Description = (string)jObject["description"],
                    Icon = (string)jObject["icon"],
                    Picture = (string)jObject["picture"],
                    Message = (string)jObject["message"],
                    CreatedTime = JTokenUtil.ParseDateTime(jObject, "created_time")
                };

                var owner = (JObject)jObject["from"];
                if (owner != null)
                {
                    link.From = new Types.LinkType.FromData()
                    {
                        Id = long.Parse((string)owner["id"]),
                        Name = (string)owner["name"]
                    };
                }

            }
            return link;
        }
    }
}
